package com.jinke.uang.ui.webview;

import android.content.DialogInterface;
import android.os.Build;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.jinke.uang.R;
import com.jinke.uang.base.BaseNetActivity;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.bean.JsOrderData;
import com.jinke.uang.utils.DebugLog;
import com.jinke.uang.utils.StringUtils;

import androidx.appcompat.app.AlertDialog;

/**
 * web页面的
 */
@Route(name = "webview页面", path = RouterMap.WEB_VIEW_PAGE)
public class WebViewActivity extends BaseNetActivity {

    private WebView webview;
    public static final String PARAMS_URL = "params_url";
    public static final String PARAMS_ORDER_DATA = "params_order_data";

    private JsOrderData orderData;
    private String TAG = WebViewActivity.class.getSimpleName();

    @Override
    protected void onUIReady() {

        if (getIntent() == null || StringUtils.isEmpty(getIntent().getStringExtra(PARAMS_URL))) {
            finish();
            return;
        }
        String mUrl = getIntent().getStringExtra(PARAMS_URL);
        orderData = (JsOrderData) getIntent().getSerializableExtra(PARAMS_ORDER_DATA);
        webview.loadUrl(mUrl);
    }

    @Override
    protected void initViews() {

        webview = findViewById(R.id.webview);
        initWebSetting();
    }

    private void initWebSetting() {
        webview.addJavascriptInterface(new JavaScript(), "jsi");
        webview.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                //对alert的简单封装
                new AlertDialog.Builder(WebViewActivity.this).
                        setTitle("Alert").setMessage(message).setPositiveButton("OK", new
                        DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).create().show();

                return super.onJsAlert(view, url, message, result);
            }
        });
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return true;
            }
        });
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    }

    @Override
    protected int getContentResId() {
        return R.layout.layout_of_webview;
    }

    @Override
    public String getPageTitle() {
        return "";
    }

    private final class JavaScript {

        @JavascriptInterface
        public void getOrderInfoData() {

            WebViewActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (webview != null && orderData != null) {
                        // Android版本变量
                        final int version = Build.VERSION.SDK_INT;

                        StringBuilder builder = new StringBuilder();
                        builder.append("javascript:call_back_getOrderInfoData(");
                        builder.append(new Gson().toJson(orderData));
                        builder.append(")");

                        if (version < 18) {
                            webview.loadUrl(builder.toString());
                        } else {
                            webview.evaluateJavascript(builder.toString(), new
                                    ValueCallback<String>() {
                                @Override
                                public void onReceiveValue(String value) {

                                }
                            });
                        }
                    }
                }
            });
        }

        @JavascriptInterface
        public void displayTraceStatus(String status) {
            if (StringUtils.isEmpty(status)) return;
            if (!"200".equalsIgnoreCase(status)) {
                // TODO: 2018/6/8 做一些  处理
                DebugLog.e(TAG, "webview geted status:" + status);
                if ("40301".equalsIgnoreCase(status)) {
                    ARouter.getInstance().build(RouterMap.LOGIN_METNOD_PAGE).navigation();
                }
            }

        }
    }
}
